package org.jgs1904.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.jgs1904.dao.UserDao;
import org.jgs1904.entity.User;
import org.jgs1904.util.DataSourceUtil;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据操作类
 *
 * @author junki
 * @date 2020年3月26日
 */
public class UserDaoImpl implements UserDao {


    @Override
    public User insert(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "insert into user(nickname,username,password,region_id,photo) value(?,?,?,?,?) ";

        BigInteger id = (BigInteger) qr.insert(sql, new ScalarHandler<>(1), user.getNickname(), user.getUsername(),
                user.getPassword(), user.getRegion_id(), user.getPhoto());

        user.setId(id.longValue());

        return user;
    }

    @Override
    public User selectOne(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());

        String sql = "select * from user where 1 = 1";
        List<Object> params = new ArrayList<>();

        if (user.getId() != null) {
            sql += " and id = ?";
            params.add(user.getId());
        }
        if (user.getNickname() != null) {
            sql += " and nickname = ?";
            params.add(user.getNickname());
        }
        if (user.getUsername() != null) {
            sql += " and username = ?";
            params.add(user.getUsername());
        }
        if (user.getPassword() != null) {
            sql += " and password = ?";
            params.add(user.getPassword());
        }


        User result = qr.query(sql, new BeanHandler<>(User.class), params.toArray());

        return result;
    }

}
